import React, { useRef, useEffect, useState } from 'react';
import { TColumn } from '@/components/editable-excel-table';
import { BaseEditorProps } from '../BaseEditor';
import styles from '../Editor.module.less';

export function InputEditor<C extends TColumn>({ value, className, onClose, onChange }: BaseEditorProps<C>) {
    const textareaRef = useRef<HTMLTextAreaElement>(null);
    const [isInitialized, setIsInitialized] = useState<boolean>(false);

    const cacheValueRef = useRef(value || '');
    const [cacheValue, setCacheValue] = useState(value || '');

    const cacheValueChangeFn = (value: string) => {
        cacheValueRef.current = value;
        setCacheValue(value);
        onChange?.(value);
    };

    // // 组件挂载时调整高度并设置光标位置
    useEffect(() => {
        // 首次激活时，将光标定位到文本末尾
        if (textareaRef.current && !isInitialized) {
            const textarea = textareaRef.current;
            const textLength = textarea.value.length;
            textarea.selectionStart = textarea.selectionEnd = textLength;
            setIsInitialized(true);
        }
    }, []);

    const handleCloseFn = () => {
        onClose?.({ type: 'leaveEditor', value: cacheValueRef.current });
    };

    const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (event.key === 'Enter') {
            // 判断是否按下了 Ctrl 键（或 Mac 上的 Cmd 键）
            const isCtrlOrCmd = event.ctrlKey || event.metaKey;
            if (isCtrlOrCmd) {
                // 允许换行
                const textarea = event.target as HTMLTextAreaElement;
                const start = textarea.selectionStart;
                const end = textarea.selectionEnd;

                // 在光标处插入换行符
                const currentValue = textarea.value;
                const newValue = currentValue.slice(0, start) + '\n' + currentValue.slice(end);

                cacheValueChangeFn(newValue);

                // 将光标移到换行符之后
                setTimeout(() => {
                    textarea.selectionStart = textarea.selectionEnd = start + 1;
                }, 0);

                event.preventDefault();
            } else {
                event.preventDefault();
                handleCloseFn();
            }
        } else if (event.key === 'Escape') {
            event.preventDefault();
            handleCloseFn();
        }
    };

    const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
        cacheValueChangeFn(event.target.value);
    };

    return (
        <>
            <textarea
                ref={textareaRef}
                value={cacheValue || ''}
                onChange={handleChange}
                onBlur={() => {
                    handleCloseFn();
                }}
                onKeyDown={handleKeyDown}
                className={`${styles.editor} ${styles.inputEditor} ${className || ''}`}
                style={{
                    resize: 'none',
                    minHeight: '20px',
                }}
                autoFocus
                placeholder="输入内容... (Ctrl+Enter换行)"
            />
        </>
    );
}
